<template>
  <section class="todoapp">
    <TodoHeader @addTask="addTaskHandler" :list="showList"></TodoHeader>
    <TodoMain @delTask="delTaskHandler" :list="showList"></TodoMain>
    <TodoFooter
      @clrTask="clrTaskHandler"
      @changeTask="changeTaskHandler"
      :list="showList"
    ></TodoFooter>
  </section>
</template>

<script>
import TodoHeader from "./components/TodoHeader";
import TodoMain from "./components/TodoMain";
import TodoFooter from "./components/TodoFooter";

export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem("todoList") || "[]"),
      isSel: "all",
    };
  },
  methods: {
    addTaskHandler(taskname) {
      this.list.push({
        id: this.list[this.list.length - 1].id + 1,
        name: taskname,
        isDone: false,
      });
    },
    delTaskHandler(id) {
      const index = this.list.findIndex((item) => item.id === id);
      this.list.splice(index, 1);
    },
    changeTaskHandler(isSel) {
      this.isSel = isSel;
    },
    clrTaskHandler() {
      // 返回一个新数组,会将循环过程中符合条件的加入到新数组
      this.list = this.list.filter((item) => item.isDone == false);
    },
  },
  computed: {
    showList() {
      if (this.isSel === "yes") {
        // 显示已完成,如果当前是 yes 就把 isDone 为 true 的数据放到新数组中返回
        return this.list.filter((item) => item.isDone === true);
      } else if (this.isSel === "no") {
        // 显示未完成,如果当前是 no 就把 isDone 为 false 的数据放到新数组中返回
        return this.list.filter((item) => item.isDone === false);
      } else {
        return this.list; // 全部显示,如果当前是 all 就全部返回
      }
    },
  },
  watch: {
    list: {
      deep: true,
      handler() {
        // 当数组的数据变化,覆盖式保存到localStorage里
        localStorage.setItem("todoList", JSON.stringify(this.list));
      },
    },
  },
};
</script>